<template>
  <MdEditor
    id="editor"
    v-model="state.text"
    @onGetCatalog="onGetCatalog"
    @onHtmlChanged="saveHtml"
  />
</template>

<script lang="ts" setup>
import { reactive, onMounted } from 'vue'
import MdEditor from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
onMounted(() => {
  initEditor()
})

const initEditor = () => {}

const onGetCatalog = (list: any) => {
  state.catalogList = list
  const tocItems: any = []
  // 标题计数器
  let count = 0
  const add = (text: string, level: number) => {
    count++

    const item = { anchor: `heading-${count}`, level, label: text }

    if (tocItems.length === 0) {
      // 第一个 item 直接 push
      tocItems.push(item)
    } else {
      let lastItem = tocItems[tocItems.length - 1] // 最后一个 item

      if (item.level > lastItem.level) {
        // item 是 lastItem 的 children
        for (let i = lastItem.level + 1; i <= 6; i++) {
          const { children } = lastItem
          if (!children) {
            // 如果 children 不存在
            lastItem.children = [item]
            break
          }

          lastItem = children[children.length - 1] // 重置 lastItem 为 children 的最后一个 item

          if (item.level <= lastItem.level) {
            // item level 小于或等于 lastItem level 都视为与 children 同级
            children.push(item)
            break
          }
        }
      } else {
        // 置于最顶级
        tocItems.push(item)
      }
    }
  }

  list.forEach((item: any) => {
    add(item.text.replace(/<\/?[a-z]+>/g, ''), item.level)
  })

  console.log(tocItems)
  state.tocItems = tocItems
}
const saveHtml = (h: string) => {
  // console.log(h)
}

const state = reactive<any>({
  //最终生成的编辑器
  editor: null,
  text: '',
  tocItems: [],
  catalogList: [],
  //默认选项
  options: {},
})
</script>

<style lang="scss" scoped>
#editor {
  width: 100%;
  height: 600px;
}
</style>
